import { reqGetShopCartList, reqDeleteShopCart, reqUpdateChecked } from '@/api'

const state = {
    shopCartList: []
}
const actions = {
    //获取购物车列表
    async getShopCartList({ commit }) {
        let res = await reqGetShopCartList()
        // console.log(res);
        if (res.code == 200) {
            commit('GETSHOPCARTLIST', res.data)
        }
    },
    //删除购物车某个商品
    async deleteShopCart({ commit }, skuId) {
        let res = await reqDeleteShopCart(skuId)
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //修改某个商品选中状态
    async updateCartChecked({ commit }, skuId, isChecked) {
        let res = await reqUpdateChecked(skuId, isChecked)
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //删除所有选中状态的商品
    deleteAllCheckedCart({ dispatch, getters }) {
        //获取购物车中所有的商品
        // console.log(getters);
        let promiseAll = []
        getters.shopCartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteShopCart', item.skuId) : ''
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    },
    //全选、全不选
    cartIsCheckedAll({ dispatch, state }, isChecked) {
        // console.log(state);
        // console.log(isChecked);
        let promiseAll = []
        state.shopCartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCartChecked', {
                skuId: item.skuId,
                isChecked
            })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const mutations = {
    GETSHOPCARTLIST(state, shopCartList) {
        state.shopCartList = shopCartList
    }
}
const getters = {
    shopCartList(state) {
        return state.shopCartList[0] || {}
    }
}

export default {
    state,
    actions,
    mutations,
    getters
}